<template>
  <el-container class="height100  domainMainContent containerHeight">
    <el-aside  class="dept-aside overflowNone  height100">
      <department_tree @node-click="onNodeClick" :key="timer"  :invalid="valid" :superiorId="searchdata.departmentid"/>
    </el-aside>

    <el-container  class="overflowYHidden height100 user borderR  ">
      <el-main class="el-mainContent  overflowYHidden  flexColumn" >
        <header_item  :headerArr="headerArr"  @onBtnClick="onBtnClick" :multipleSelection="multipleSelection" ref="headerItem"/>
          <div class=" containerContentHeight">
            <el-row ref="userListSearch">
          <el-col>
            <search_item :searchItemArr="searchItemArr" @searchItemData="searchItemData"/>
          </el-col>
        </el-row>
        <!-- 用户列表 -->
        <el-table :data="tableData.datas"
              stripe
              @row-click="onRowClick"
              class="Trpointer elTags userTable" 
              ref="multipleTable"
              @selection-change="handleSelectionChange"
              header-cell-class-name="tableHeaderbg"
              size="small"
              :row-key="handleReserve" 
              tooltip-effect="light"
              :height="tableListConHeight">
          <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
          <el-table-column prop="name" :label="$t('username')" width="160"></el-table-column>
          <el-table-column prop="loginno" :label="$t('loginno')" width="100"></el-table-column>
          <el-table-column prop="email" :label="$t('email')" >
            <template slot-scope="scope">
              <span v-if="scope.row.emailPublic">{{scope.row.email}}</span>
              <span v-else class="orangeColor">{{$t('no_public')}}</span>
            </template>
          </el-table-column>
          <el-table-column  :label="$t('role')" width="200">
            <template slot-scope="scope">
              <el-popover
                placement="top"
                title="角色"
                trigger="hover"
              >
              <div class="drawerTags">
                <el-tag type="success" disable-transitions  v-for="(ite,index) in scope.row.roles" :key="index+ite.id"  class="elTag">
               <span :title="ite.name">{{ite.name}}</span>
              </el-tag>
              </div>
              <span slot="reference">
                <div v-if="scope.row.roles && scope.row.roles.length>0" class="columnRole">
                      <span v-for="(ite,index) in scope.row.roles" :key="ite.id+index">
                     {{ite.name}}
                      </span>
                  </div>
                </span>
                
                </el-popover>
            </template>
          </el-table-column>
          <el-table-column :label="$t('superior_name')" prop="superior.name" width="150"></el-table-column>
          <el-table-column v-for="(elm,index) in fieldextendsList" :key="index" :prop="elm.name" :label="elm.label"></el-table-column>
          <el-table-column prop="status" :label="$t('status')">
            <template slot-scope="scope">
              <span v-if="scope.row.status==0" class="redColor">{{$t('resign')}}</span>
              <span v-else class="greenColor">{{$t('on_job')}}</span>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
         ref="paginationHeight"
          @size-change="handleSizeChange"
          @current-change="searchTableData"
          :current-page.sync="searchdata.currpage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="searchdata.pagelines"
          layout="prev, pager, next, total, sizes"
          background
          :total="tableData.rowCount?tableData.rowCount:0"
          
        ></el-pagination>
          </div>
        <!-- 分页 -->
      </el-main>

      <!-- 新建编辑的时候出现 -->
      <user_detail 
            ref="editDetail"
            :visible.sync="detailVisible"
            v-if="detailVisible"
            @refresh="refresh"
            @exit="onExit"
            :detail="content"
            :dialogTitle="dialogTitle"
            />
    </el-container>
    <fileUpload :visible.sync="fileUploadVisible" v-if="fileUploadVisible" :nowOption="nowOption" @success="successUser"/>
  </el-container>
</template>

<script>
import department_tree from "@/components/department_tree.vue";
import user_detail from "@/components/user_detail.vue";
import search_item from "@/components/common/search_item.vue";
import fileUpload from "@/components/fileUpload.vue";
import { pxToRemScale } from '../utils'
import {delMsg} from '../utils/elementui'
export default {
  components: {
    department_tree,
    user_detail,
    fileUpload,
    search_item
  },
  data() {
    return {
      searchdata: {
        domainid: this.$route.query.domainid,
        departmentid: "",
        currpage: 1,
        pagelines: 10,
        orderby: "orderByNo",
        data:{
          searchWord: "",
          status:'',
          fieldExtends: {}
        }
      },
      content: {}, //部门信息对象
      userSelectVisible: false,
      currentEditField: "", //PROXY
      tableData: [],
      multipleTable:[],
      valid:false,
      fieldextendsList:[],
      fieldextends: [],
      multipleSelection:[],
      fileUploadVisible:false,
      nowOption:"import",
      tableListConHeight:null,
      treeListConHeight:null,
      isSecret:false,
      isAdmin: false,//是否是系统管理员
      SupportSearchList:[],
      detailVisible: false, // 用户信息详情弹窗
      dialogTitle: '', // 弹窗标题
      diabledResign:false,//用户状态失效
      timer:'',
      searchItemArr:[],
      statusArr:[
        {label:'',value:''},
        {label:this.$t('on_job'),value:1},
        {label:this.$t('resign'),value:0}
      ],
      headerArr:{}
    };
  },
  watch:{
    diabledResign(newVal,oldVal){
        this.headerArr.btnArr.splice(this.headerArr.btnArr.length-1,1,{btnDisabled:newVal,name:'resign',label:this.$t('resign')})
    }
  },
  computed:{
  },
  created() {
    if (this.$store.state.currentUser.isOpenSecurity && this.$store.state.currentUser.type == 'secret') {
      this.isSecret= true;//是否是安全保密员
    }
    if(this.$store.state.currentUser.isOpenSecurity && this.$store.state.currentUser.type == 'admin') {
      this.isAdmin = true;//是否是系统管理员
    }
    this.searchTableData();
    //在这里对传过去的参数赋值初始
    this.searchItemArr=[
      {type:'input',name:'searchWord',placeholder:this.$t('user_name')+'/'+this.$t('loginno')+'/'+this.$t('superior_name')+'/'+this.$t('cell_phone')},
      {type:'select',name:'status',placeholder:this.$t('placeholder_select'),arr:this.statusArr}
    ]
    // let dataJson={ 
    //   currpage:1,
    //   pagelines:999,
    //   data:{
    //     type:"",
    //     fortable:"tableUser",
    //     domainid: this.$route.query.domainid,
    //     belong:"All"
    //   }
    // }
    // this.$api.getFieldExtends(
    //   dataJson,
    //   {
    //     onSucess: resp => {
    //       let temp=[]
    //       resp.data.data.datas.forEach(elm=>{
    //         if(elm.enabel){
    //           this.fieldextendsList.push(elm);
    //         }
    //         if(elm.isSupportSearch){
    //           this.SupportSearchList.push(elm);
    //         }
    //       })
    //       //处理扩展字段
    //       this.SupportSearchList.forEach(item=>{
    //           temp.push({type:'input',name:item.name,placeholder:item.label})
    //       })
    //       this.searchItemArr=[...this.searchItemArr,...temp]
    //     }
    //   }
    // );
    this.headerArr={iconfont:'icon-yonghuda',content:this.$t('user_list'),btnArr:[{name:'export',label:this.$t('user_all_export')}] }

    let arr=[{type:"primary",name:'new',label:this.$t('new')},{name:'import',label:this.$t('user_import')}]
    let arr1 = []
    if(this.isAdmin) { //系统管理员没有失效按钮，其他都有
      arr1 = [{type:"danger",name:'del',label:this.$t('del')}]
    }else {
      arr1=[{type:"danger",name:'del',label:this.$t('del')},{btnDisabled:false,name:'resign',label:this.$t('resign')}]
    }
    this.headerArr.btnArr=[...arr,...this.headerArr.btnArr,...arr1]
    
  },
  mounted(){
    debugger
    // let temp=pxToRemScale(this.$refs.userListSearch.$el.getClientRects()[0].height+this.$refs.paginationHeight.$el.getClientRects()[0].height)
    // headerItem
    // let temp=pxToRemScale(this.$refs.userListSearch.$el.getClientRects()[0].height+this.$refs.paginationHeight.$el.getClientRects()[0].height + this.$refs.headerItem.$el.getClientRects()[0].height)
    // this.tableListConHeight= `calc(100% - ${temp}rem)`
    this.tableListConHeight = document.body.clientHeight - this.$refs.userListSearch.$el.getClientRects()[0].height - this.$refs.paginationHeight.$el.getClientRects()[0].height - this.$refs.headerItem.$el.getClientRects()[0].height -32
  },
  methods: {
    onBtnClick(name){
      debugger
      if(name=='new'){this.onCreateBtnClick()}
      else if(name=='export'){this.onExportBtnClick()}
      else if(name=='import'){this.onImportBtnClick()}
      else if(name=='del'){this.onDeleteBtnClick()}
      else if(name=='resign'){this.onDimissionBtnClick()}
    },
    onImportBtnClick(){
      this.fileUploadVisible=true;
    },
     onExportBtnClick(){
      debugger
      this.$api.exportUser(
        () => {
          this.$message({
            showClose: true,
            message: this.$t("export_success"),
            type: "success"
          });
        }
      );
    },
    onDimissionBtnClick(){
      const selectData = this.multipleSelection;
      if(selectData.length == 0){
        this.$message({
          showClose: true,
          message: this.$t("msg_select_user"),
          type: "error"
        });
      }else{
        this.$api.abandonment(
          selectData,
          {
            onSucess: resp => {
              if(resp.data.errcode == 0){
                this.$message({
                  showClose: true,
                  message: resp.data.data,
                  type: "success"
                });
                this.searchTableData();
              }
            }
          }
        )
      }
    },
    handleSelectionChange(val){
      let flag=false
      var arr = [];
       val.forEach((val) => {
         if(val.status=='0'){
           //其中一个用户状态失效，则失效按钮不可用
           flag=true
         }
        this.tableData.datas.forEach((v) => {
          if(val.id == v.id){
            arr.push(val.id)
          }
        })
      })   
      this.diabledResign=flag
      this.multipleSelection = arr;
    },

    handleReserve(row){
      return row.id
    },

    onExit(){
      this.detailVisible = false;
      this.searchTableData();
      this.$forceUpdate()
    },
    
    onNodeClick(dept) {
      this.searchdata.departmentid = dept.id;
      this.searchTableData();
      this.showList();
    },
    
    onProxyUserBtnClick() {
      this.currentEditField = "proxyUser";
      this.userSelectVisible = true;
    },

    onSuperiorUserBtnClick() {
      this.currentEditField = "superior";
      this.userSelectVisible = true;
    },

    onSelectUserOk(users) {
      if (users && users.length > 0) {
        this.content[this.currentEditField] = users[0];
      }
    },
    showDetail(user) {
      this.content=JSON.parse(JSON.stringify(user));
      this.detailVisible = true;
    },

    showList() {
      this.detailVisible = false;
    },

    //新建
    onCreateBtnClick() {
      this.dialogTitle = this.$t('user_new');
      this.showDetail({startProxyTime:"",endProxyTime:"",status:1,permissionType:"public",orderByNo:0,roleDepartments:[], confirmpwd: '',departmentUser: false,isCreate:true});
    },

    onDeleteBtnClick(){
      if(this.multipleSelection.length>0){
        this.$api.deleteUser({
          data:this.multipleSelection
        },{
          onSucess:resp =>{
            if(resp.data.errcode==0){
              this.$refs.multipleTable.clearSelection()//手动清除
              this.$message({
                showClose: true,
                message: this.$t('msg_del_success'),
                type: "success"
              });
              this.searchdata.data.name="";
              //判断是否在最后一页删除内容
              if(this.tableData.datas.length==1){
                this.searchdata.currpage-=1;
                if(this.searchdata.currpage<=1){
                  this.searchdata.currpage=1
                }
              }
              this.searchTableData()
            }else{
              this.$message({
                  showClose: true,
                  message: resp.data.errmsg,
                  type: "error"
                });
            }
          },
          onError:function(){

          }
        })
      }else{
        this.$message({
          showClose: true,
          message: this.$t("msg_select_user"),
          type: "error"
        });
      }
    },
    handleSizeChange(size){
      this.searchdata.pagelines=size;
      this.searchTableData();
    },
    searchItemData(val){
      //处理扩展字段
      this.searchdata={
        ...this.searchdata,
        data:{
          searchWord:val.searchWord,
          status:val.status,
          fieldExtends:{
            ...val
          }
        },
      }
      //删除fieldextends中的name属性
      delete this.searchdata.data.fieldExtends.searchWord
      delete this.searchdata.data.fieldExtends.status
      this.searchTableData()
    },
    searchTableData() {
      this.$api.getUsers(this.searchdata, {
        onSucess: resp => {
          debugger
          this.tableData = resp.data.data;
           this.$nextTick(() => {
            this.$refs.multipleTable.doLayout()
          })
        }
      });

      
    },

    onRowClick(row) {
      this.dialogTitle = this.$t('user_edit');
      this.showDetail(row)
    },

    refresh(){
      this.detailVisible = false;
      this.searchTableData();
      this.$forceUpdate()
    },
    resetSearchTableData(){
      this.searchdata={
        domainid: this.$route.query.domainid,
        departmentid: this.searchdata.departmentid,
        currpage: 1,
        pagelines: 10,
        orderby: "",
        data:{
          searchWord: "",
          status:'',
          fieldExtends: {}
        }
      }
      this.searchTableData();
    },
    successUser(){
      this.searchdata.departmentid=''
      this.timer=new Date().getTime()
      this.searchTableData();
    }
  },
};
</script>